package com.lenovo.redission.redission.lock;

import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;


@Log4j2
@Data
public class RedissonDistributedLock implements IDistributedLock {

    @Autowired(required = false)
    private RedissonClient redissonClient;


    @Override
    public boolean tryLock(String lockKey, long expireTime, TimeUnit timeUnit) throws InterruptedException {
        RLock rLock = redissonClient.getLock(lockKey);
        return rLock.tryLock(-1, expireTime, timeUnit);
    }

    @Override
    public boolean tryLockWait(String lockKey, long expireTime, long waitTime, TimeUnit timeUnit) throws InterruptedException {
        RLock rLock = redissonClient.getLock(lockKey);
        return rLock.tryLock(waitTime, expireTime, timeUnit);
    }

    @Override
    public void lock(String lockKey) {
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock();
    }

    @Override
    public void unlock(String lockKey) {
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            rLock.unlock();
        } catch (IllegalMonitorStateException e) {
            if (e.getMessage().startsWith("attempt to unlock lock, not locked by current thread by node id")) {
                log.error(e.getMessage());
                return;
            }
            log.error(e);
        } catch (Exception e) {
            log.error(e);
        }
    }

}
